<template>
  <div>
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="instrumentOpen" title="仪器使用记录" width="80%">
      <el-row>
        <p class="pinformation">仪器使用记录列表</p>
        <p class="totalStyle">共 {{ recordInsterList.length }} 条数据</p>
        <el-row style="padding-bottom: 5px; margin-left: 20px" v-if="!isDisable">
          <el-button link @click="handleRecordAdd">新增</el-button>
        </el-row>
      </el-row>
      <el-table :data="recordInsterList" max-height="550px">
        <el-table-column label="仪器名称" align="center" prop="name" />
        <el-table-column label="仪器型号" align="center" prop="code" width="160" />
        <el-table-column label="仪器编号" align="center" prop="number" width="100" />
        <el-table-column label="开始时间" align="center" prop="startDate" width="155">
          <template #default="scope">
            {{ scope.row.startDate }} {{ scope.row.startTime }}
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endDate" width="155">
          <template #default="scope">
            {{ scope.row.endDate }} {{ scope.row.endTime }}
          </template>
        </el-table-column>
        <el-table-column label="使用前仪器状态" align="center" prop="useBefore" width="130">
          <template #default="scope">
            {{ scope.row.useBefore ? "异常" : "正常" }}
          </template>
        </el-table-column>
        <el-table-column label="使用后仪器状态" align="center" prop="useAfter" width="130">
          <template #default="scope">
            {{ scope.row.useAfter ? "异常" : "正常" }}
          </template>
        </el-table-column>
        <el-table-column label="显示在原始记录表中" align="center" prop="show" width="150">
          <template #default="scope">
            <el-checkbox v-model="scope.row.show" :disabled="isDisable" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100" v-if="!isDisable">
          <template #default="scope">
            <el-button link @click="editRecord(scope.row)">编辑</el-button>
            <el-button link @click="delRecord(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="save" v-if="!isDisable">确定</el-button>
          <el-button type="danger" @click="instrumentOpen = false" v-if="!isDisable">取消</el-button>
          <el-button type="danger" v-if="isDisable" @click="instrumentOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="recordFormOpen" :title="recordFormTitle" @close="dialogClose" width="1100">
      <el-form :model="recordForm" ref="recordRef" :rules="recordRules" label-width="80">
        <el-row>
          <el-col :span="12">
            <el-form-item label="仪器名称：" prop="instrumentId">
              <el-select style="width: 100%" v-model="recordForm.instrumentId" clearable filterable remote reserve-keyword
                placeholder="请输入仪器名称或仪器型号或仪器编号" remote-show-suffix :remote-method="remoteMethod1"
                @change="instrumentIdChange" :loading="loading2">
                <el-option v-for="(item, index) in instrList" :key="item.instrumentId" :value="item.instrumentId"
                  :label="item.number + '　' + item.code + '　' + item.name">
                  {{ item.number }}&nbsp;{{ item.name }}&nbsp;{{ item.code }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仪器型号：">
              {{ recordForm.instrumentType }}
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="仪器编号：">
              {{ recordForm.instrumentCode }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="开始日期：" prop="startDate">
              <el-date-picker v-model="recordForm.startDate" placeholder="请选择开始日期" style="width: 100%" type="date"
                value-format="YYYY-MM-DD" @change="startDateChange" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开始时间：" prop="startTime">
              <!-- default-value="" -->
              <!-- :disabled-hours="disabledHours"
              :disabled-minutes="disabledMinutes" -->
              <el-time-picker v-model="recordForm.startTime" placeholder="请选择开始时间" format="HH:mm" value-format="HH:mm"
                @change="startTimeChange" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束日期：" prop="endDate">
              <el-date-picker v-model="recordForm.endDate" placeholder="请选择结束日期" style="width: 100%" type="date"
                value-format="YYYY-MM-DD" @change="endDateChange" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <!-- :disabled-hours="disabledHours1"
            :disabled-minutes="disabledMinutes1" -->
            <el-form-item label="结束时间：" prop="endTime">
              <el-time-picker v-model="recordForm.endTime" placeholder="请选择结束时间" format="HH:mm" value-format="HH:mm"
                @change="endTimeChange" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="使用前仪器状态：" label-width="120">
              <el-row justify="center">
                <el-radio v-model="recordForm.useBefore" :label="0">正常</el-radio>
                <el-radio v-model="recordForm.useBefore" :label="1">异常</el-radio>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="使用后仪器状态：" label-width="120">
              <el-row justify="center">
                <el-radio v-model="recordForm.useAfter" :label="0">正常</el-radio>
                <el-radio v-model="recordForm.useAfter" :label="1">异常</el-radio>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="recordSave">保存</el-button>
          <el-button type="danger" @click="recordFormOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  getRecordList,
  getInstrumentList,
  labInstrumentUsePost,
  getLabInstrumentUseForm,
  delRecordAxios,
  getMsg,
  getDateList,
  isShowSave
} from "@/api/lab/labMethod";
const recordRules = ref({
  instrumentId: [
    { required: true, message: "仪器名称不能为空", trigger: "blur" },
  ],
  startDate: [
    { required: true, message: "开始日期不能为空", trigger: "blur" },
  ],
  startTime: [
    { required: true, message: "开始时间不能为空", trigger: "blur" },
  ],
  endDate: [
    { required: true, message: "结束日期不能为空", trigger: "blur" },
  ],
  endTime: [
    { required: true, message: "结束时间不能为空", trigger: "blur" },
  ],
});
const { proxy } = getCurrentInstance();
const recordForm = ref({ useBefore: 0, useAfter: 0 });
const instrumentOpen = ref(false);
const recordFormOpen = ref(false);
const recordFormTitle = ref("");
const recordInsterList = ref([]);

const props = defineProps({
  lMId: {
    type: String,
  },
  useTypeId: {
    type: Number,
  },
});

// ---------------------------仪器使用记录--------------------------
const isDisable = ref(false)

const instrList = ref([]);
function handleUseRecord(isDisable1) {
  instrumentOpen.value = true;
  isDisable.value = isDisable1 || false
  getRecordList({ relId: props.lMId }).then((res) => {
    recordInsterList.value = res.data;
    recordInsterList.value.forEach(item => {
      if (item.isShow) item.show = true
      if (!item.isShow) item.show = false
    })
  });
}

defineExpose({
  handleUseRecord
})

function handleRecordAdd() {
  recordFormOpen.value = true;
  recordFormTitle.value = "新增仪器使用记录";
  if (recordInsterList.value.length > 0) {
    let firstForm = recordInsterList.value[0]
    recordForm.value.startDate = firstForm.startDate
    recordForm.value.startTime = firstForm.startTime
    recordForm.value.endDate = firstForm.endDate
    recordForm.value.endTime = firstForm.endTime
  }
}

function recordSave() {
  proxy.$refs["recordRef"].validate((valid) => {
    if (valid) {
      recordForm.value.relId = props.lMId;
      getMsg(recordForm.value).then(response => {
        if (response.msg != "操作成功") {
          proxy.$modal.confirm(response.msg).then(() => {
            if(!recordForm.value.isShow && typeof recordForm.value.isShow != "number"){
              recordForm.value.isShow = 1;
            }
            labInstrumentUsePost(recordForm.value).then(() => {
              recordFormOpen.value = false;
              getRecordList({ relId: props.lMId }).then((res) => {
                recordInsterList.value = res.data;
                recordInsterList.value.forEach(item => {
                  if (item.isShow) item.show = true
                  if (!item.isShow) item.show = false
                })
              });
            });
          })
          return
        }
        if(!recordForm.value.isShow && typeof recordForm.value.isShow != "number"){
          recordForm.value.isShow = 1;
        }
        labInstrumentUsePost(recordForm.value).then((response) => {
          recordFormOpen.value = false;
          getRecordList({ relId: props.lMId }).then((res) => {
            recordInsterList.value = res.data;
            recordInsterList.value.forEach(item => {
              if (item.isShow) item.show = true
              if (!item.isShow) item.show = false
            })
          });
        });
      })
    }
  });
}

function editRecord(row) {
  recordFormOpen.value = true;
  recordFormTitle.value = "编辑仪器使用记录";
  getLabInstrumentUseForm(row.useId).then((res) => {
    recordForm.value = res.data;
    instrList.value = [
      {
        code: res.data.code,
        number: res.data.number,
        name: res.data.name,
        instrumentId: res.data.instrumentId,
      },
    ];
    recordForm.value.instrumentType = res.data.code;
    recordForm.value.instrumentCode = res.data.number;
  });
}

function delRecord(row) {
  proxy.$modal.confirm("确定要删除吗？").then(() => {
    delRecordAxios(row.useId).then((res) => {
      proxy.$modal.msgSuccess("删除成功");
      getRecordList({ relId: props.lMId }).then((res) => {
        recordInsterList.value = res.data;
        recordInsterList.value.forEach(item => {
          if (item.isShow) item.show = true
          if (!item.isShow) item.show = false
        })
      });
    });
  });
}

const loading2 = ref(false);
function remoteMethod1(val) {
  if (val) {
    loading2.value = true;
    setTimeout(() => {
      let params = { instrumentCode: val };
      if(props.useTypeId || typeof props.useTypeId == 'number'){
        params.useTypeId = props.useTypeId;
      }
      getInstrumentList(params).then((res) => {
        loading2.value = false;
        instrList.value = res.data;
      });
    }, 200);
  } else {
    instrList.value = [];
  }
}

function instrumentIdChange(val) {
  if (!val) {
    recordForm.value.instrumentType = "";
    recordForm.value.instrumentCode = "";
    return;
  }
  getInstrumentList({ instrumentId: val }).then((res) => {
    recordForm.value.instrumentType = res.data[0].code;
    recordForm.value.instrumentCode = res.data[0].number;
  });
}

function dialogClose() {
  recordForm.value = { useBefore: 0, useAfter: 0 };
  instrList.value = [];
  proxy.$refs["recordRef"].clearValidate();
}

// const disabledHours = () => {
//   let list = [];
//   dateList.value.forEach((item) => {
//     list.concat(makeRange(item.hour.start, item.hour.end));
//   });
//   return list;
// };
// const disabledMinutes = (hour) => {
//   var minute;
//   dateList.value.forEach((item) => {
//     for (const item1 of item.min) {
//       if (hour == item1.hour) {
//         minute = makeRange(item1.min.start, item1.min.end);
//         break;
//       }
//     }
//   });
//   return minute;
// };

// const disabledHours1 = () => {
//   let list = [];
//   dateList1.value.forEach((item) => {
//     if (item.hour.start && item.hour.end) {
//       list.concat(makeRange(item.hour.start, item.hour.end));
//     }
//   });
//   return list;
// };
// const disabledMinutes1 = (hour) => {
//   var minute;
//   dateList1.value.forEach((item) => {
//     for (const item1 of item.min) {
//       if (hour == item1.hour) {
//         minute = makeRange(item1.min.start, item1.min.end);
//         break;
//       }
//     }
//   });
//   return minute;
// };

const dateList = ref([]);
const dateList1 = ref([]);

const makeRange = (start, end) => {
  const result = [];
  for (let i = start; i <= end; i++) {
    result.push(i);
  }
  return result;
};

function startDateChange() {
  delete recordForm.value.startTime;
  delete recordForm.value.endTime;
  if (recordForm.value.startDate) {
    if (!recordForm.value.endDate) {
      recordForm.value.endDate = recordForm.value.startDate;
      endDateChange();
    } else if (recordForm.value.endDate < recordForm.value.startDate) {
      recordForm.value.endDate = recordForm.value.startDate;
      endDateChange();
    }
    getDateList({
      instrumentId: recordForm.value.instrumentId,
      useDate: recordForm.value.startDate,
    }).then((res) => {
      dateList.value = res.data;
    });
  }
}

function endDateChange() {
  delete recordForm.value.endTime;
  if (recordForm.value.endDate) {
    if (recordForm.value.endDate < recordForm.value.startDate) {
      recordForm.value.endDate = recordForm.value.startDate;
    }
    getDateList({
      instrumentId: recordForm.value.instrumentId,
      useDate: recordForm.value.endDate,
    }).then((res) => {
      dateList1.value = res.data;
    });
  }
}

function startTimeChange() {
  if (recordForm.value.endDate == recordForm.value.startDate) {
    if (!recordForm.value.endTime) {
      recordForm.value.endTime = recordForm.value.startTime;
    } else if (recordForm.value.endTime < recordForm.value.startTime) {
      recordForm.value.endTime = recordForm.value.startTime;
    }
  }
}

function endTimeChange() {
  if (recordForm.value.endDate == recordForm.value.startDate) {
    if (recordForm.value.endTime < recordForm.value.startTime) {
      recordForm.value.endTime = recordForm.value.startTime;
    }
  }
}

const emit = defineEmits(["save"])

function save() {
  if (recordInsterList.value.length == 0) {
    emit("save","empty_instrument");
    instrumentOpen.value = false;
    return
  }
  let temp = recordInsterList.value.map((item) => {
    if (item.show) item.isShow = 1
    if (!item.show) item.isShow = 0
    return { isShow: item.isShow, useId: item.useId }
  })
  isShowSave(temp).then(res => {
    proxy.$modal.msgSuccess("保存成功")
    instrumentOpen.value = false
    emit("save")
  })
}
</script>
